【C++编程】宏offsetof

函数 offsetof 的用法

offsetof()是一个宏, 返回 结构体成员 在内存中的偏移量。

1. 实例

#include<stdio.h>
#include<stddef.h>
struct S
{
	char c1;
	int a;
	char c2;
};
int main()
{
	//offsetof()返回 结构体成员 在内存中的偏移量
	printf("%d\n", offsetof(struct S, c1));//0
	printf("%d\n", offsetof(struct S, a));//4
	printf("%d\n", offsetof(struct S, c2));//8
	return 0;
}

2.示例

#include<stdio.h>
struct S
{
	char c1;
	int a;
	char c2;
};
//将结构体首地址设置为0,则结构体成员 的地址 就是对应的偏移量。
#define OFFSETOF(struct_name,member_name) (int)&(((struct_name*)0)->member_name)
int main()
{
	printf("%d\n", OFFSETOF(struct S, c1));//0
	printf("%d\n", OFFSETOF(struct S, a));//4
	printf("%d\n", OFFSETOF(struct S, c2));//8
	return 0;
}

 

posted @ 2018-05-12 15:48  苏格拉底的落泪  阅读(6563)  评论(0编辑  收藏  举报